<template>
  <div>
    <el-button @click="showDialog" type="primary">选择地址</el-button>

    <el-dialog
      :visible.sync="dialog"
      append-to-body
      title="选择地址"
      width="1000px"
    >
      <div>
        <div class="mgb20">
          <add-address-dialog :data="false" @saveUserAddress="getData"></add-address-dialog>
        </div>
        <div class="address-list">
          <div class="address-box" v-for="item in data" :key="item.id" :class="item.id === currentRowId ? 'choose' : ''" @click="chooseRow(item)">
            <div class="address-name">
              {{item.receiveName}} - {{item.phone}}
            </div>
            <div class="address-address">
              {{item.address}}
            </div>
            <div v-if="item.isDefault" class="address-default">
              <el-tag>默认</el-tag>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="submit">确认</el-button>
        <el-button @click="dialog = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {getAddressList} from "@/api/userAddress";
import AddAddressDialog from "@/views/userAddress/components/AddAddressDialog";

export default {
  name: 'ChooseAddress',
  components: {AddAddressDialog},
  props:{
    // 当前选择的地址
    chooseId: {

    }
  },
  computed: {
    currentRow(){
      return this.data.find(item => item.id === this.currentRowId)
    }
  },
  data(){
    return {
      data: [],
      dialog: false,
      currentRowId: 0,
    }
  },
  created() {
    this.getData()
  },
  methods: {
    getData(){
      getAddressList().then(res => {
        this.data = res.data
        if(!this.chooseId){
          this.setCurrentRowId()
          this.submit()
        }
      })
    },
    showDialog(){
      this.dialog = true
      this.setCurrentRowId()
    },
    setCurrentRowId(){
      this.currentRowId = this.chooseId ? this.chooseId : this.data[0].id
    },
    chooseRow(row){
      console.log(row)
      this.currentRowId = row.id
    },
    submit(){
      this.$emit('submitAddress', this.currentRow)
      this.dialog = false
    }
  },

}
</script>

<style scoped lang="scss">
.address-list{
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  justify-content: flex-start;
  .address-box{
    width: 200px;
    min-height: 100px;
    margin-right: 20px;
    margin-bottom: 20px;
    border: 1px solid #ccc;
    padding: 10px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    border-radius: 5px;
    cursor: pointer;
    position: relative;
    .address-name{
      font-size: 14px;
    }
    .address-address{
      color: #AAAAAA;
    }
  }
  .address-box.choose{
    background: #fff2e8;
    border: 1px solid #fa541c;
  }
  .address-default{
    position: absolute;
    right: 0;
    top: 0;
  }
}
</style>
